﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Data.Schema.SchemaModel;
using TFDP.Common;

namespace TFDP.VsPackage.Services
{
    public interface IProjectNotifierService
    {
        event EventHandler<QueueChangedEventArgs> QueueChanged;
        event EventHandler<ProjectClosedEventArgs> ProjectClosed;
        IEnumerable<IProcessor> QueryProcessors();
    }

    public class ProjectNotifierService : IProjectNotifierService
    {
        private List<IProcessor> processors;

        public ProjectNotifierService()
        {
            this.processors = new List<IProcessor>();
        }

        internal void NotifyQueueChanged(IProcessor processor)
        {
            RaiseQueueChanged(processor);
        }
        
        internal void NotifyProjectClosed(IProcessor processor)
        {
            RaiseProjectClosed(processor);
        }
        
        public event EventHandler<QueueChangedEventArgs> QueueChanged;

        private void RaiseQueueChanged(IProcessor processor)
        {
            if (QueueChanged != null)
                QueueChanged(this, new QueueChangedEventArgs(processor));
        }

        public event EventHandler<ProjectClosedEventArgs> ProjectClosed;

        private void RaiseProjectClosed(IProcessor processor)
        {
            if (this.processors.Contains(processor))
                this.processors.Remove(processor);

            if (ProjectClosed != null)
                ProjectClosed(this, new ProjectClosedEventArgs(processor));
        }

        public IEnumerable<IProcessor> QueryProcessors()
        {
            return this.processors
                .Where(p => p != null)
                .Select(p => p);
        }

        internal void RegisterProcessor(IProcessor processor)
        {
            var matches = processors
                .Where(p => p.ProjectName == processor.ProjectName)
                .Any();

            if(!matches)
                this.processors.Add(processor);
        }
    }
}
